//
//  WKBaseViewController.swift
//  DollBuy
//
//  Created by 郑东喜 on 2016/12/9.
//  Copyright © 2016年 郑东喜. All rights reserved.
//  WKWebView基础类

import UIKit
import WebKit

///检测蜂窝权限
import CoreTelephony


var shopList : String?

/// 当用户留言完毕后，出发此函数，跳转至交流区最初页面
protocol WKBaseDelegate {
    func server()
}

class WKBaseViewController: BaseViewController,WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler,UIScrollViewDelegate {
    
    var webView: WKWebView!
    
    ///分享视图
    var shareView    :YSJShareView!
    
    
    //全局链接变量
    var url : String = ""
    
    var netStatus : String = ""
    
    
    var refreshControl = UIRefreshControl()
    var progressView = UIProgressView()
    var urlRequestCache = NSURLRequest()
    
    //分享变量
    var titleStr : String = ""
    var desc : String = ""
    var link : String = ""
    var imgURL : String = ""
    
    //检查刷新加载
    var situationMark = "loadFailed"
    
    ///权限按钮
    let AutoCellularbtn = UIImageView()
    
    //刷新图片
    var imgView = UIImageView()
    
    //取出token
    var token : String = ""
    
    
    //    var viewController = ShareViewController()
    
    //代理
    var wkDelegate : WKBaseDelegate?
    
    /// 断网图片单机刷新事件
    func imgSEL() -> Void {
        
        view.addSubview(self.webView)
        
        self.webView.load(self.urlRequestCache as URLRequest)
    }
    
    ///移除蜂窝权限图片，界面消失的时候
    override func viewWillDisappear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        AutoCellularbtn.removeFromSuperview()
    }
    
    /// 视图将要出现时，取token
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        
        ///先检查网络类型，只在蜂窝网络状态下进行提示---用户开启网络权限
        //根据是否有网络状态加载断网图片
        StatusBarCheck.shared.networkingStatesFromStatebar { (result) in
            
            ///不是wifi，进行检查
            if result != "wifi" {
                ///应用启动后，检测应用中是否有联网权限
                if #available(iOS 9.0, *) {
                    
                    let culluarData = CTCellularData()
                    
                    culluarData.cellularDataRestrictionDidUpdateNotifier = { (state : CTCellularDataRestrictedState) -> Void in
                        
                        ///网络受限
                        if state.hashValue == 1 {
                            
                            DispatchQueue.main.async {
                                self.AutoCellularbtn.frame = CGRect(x:SW * 0.25 , y: SH * 0.25, width: SW * 0.5, height: SW * 0.5)
                                
                                self.AutoCellularbtn.image = UIImage.init(named: "sulution")
                                self.AutoCellularbtn.isUserInteractionEnabled = true
                                
                                let soluGes = UITapGestureRecognizer.init(target: self, action: #selector(WKBaseViewController.gotoSet))
                                
                                self.AutoCellularbtn.addGestureRecognizer(soluGes)
                                
                                self.view.addSubview(self.AutoCellularbtn)
                                
                                return
                            }
                            
                            ///网络未受限
                        } else {
                            //取出本地token，进行拼接,token为空不为空，均传到服务器
                            if (localSave.object(forKey: userToken) != nil) {
                                self.token = localSave.object(forKey: userToken) as! String
                                
                            } else {
                                self.token = ""
                            }
                            
                        }
                        
                    }
                    
                }
                ///是wifi，正常执行
            } else {
                
            }
        }
        
        
        //取出本地token，进行拼接,token为空不为空，均传到服务器
        if (localSave.object(forKey: userToken) != nil) {
            token = localSave.object(forKey: userToken) as! String
            
        } else {
            token = ""
        }
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        self.setUI()
    }
    
    
    /// 监听进度条值变化
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if (keyPath == "estimatedProgress") { // listen to changes and updated view
            progressView.isHidden = webView.estimatedProgress == 1
            progressView.setProgress(Float(webView.estimatedProgress), animated: true)
        }
    }
    
    // MARK:- wkwebview代理方法
    /// 没网络发起
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        
        //赋值，表示失败，供刷新使用
        self.situationMark = "true"
        
        
        netStatus = "false"
        
        imgView = UIImageView()
        
        //手动设置没网络图片位置
        imgView.frame = CGRect(x:SW * 0.25 , y: SH * 0.25, width: SW * 0.5, height: SW * 0.5)
        
        
        
        imgView.image = UIImage.init(named: "lostNet")
        
        imgView.contentMode = UIViewContentMode.scaleAspectFit
        
        let tag = UITapGestureRecognizer.init(target: self, action:#selector(WKBaseViewController.imgSEL))
        
        imgView.isUserInteractionEnabled = true
        
        imgView.addGestureRecognizer(tag)
        
        //根据是否有网络状态加载断网图片
        StatusBarCheck.shared.networkingStatesFromStatebar { (result) in
            
            if result == "notReachable" {
                self.imgView.image = UIImage.init(named: "lostNet")
                self.view.addSubview(self.imgView)
                
            } else {
                return
            }
        }
        
        refreshControl.endRefreshing()
    }
    
    
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        self.navigationItem.title = "加载中~~~"
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        
        decisionHandler(.allow)
    }
    
    //获取标题
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        //XFLog(message: webView.estimatedProgress)
        
        //改变刷新标识符
        self.situationMark = "false"
        
        netStatus = "true"
        
        //移除没有网络提示图片
        DispatchQueue.main.async {
            self.imgView.removeFromSuperview()
        }
        
        
        self.progressView.progress = Float(webView.estimatedProgress)
        self.navigationItem.title = self.webView.title
        
        
        //走满进度条，停止选择
        if self.webView.isLoading == false {
            UIView.animate(withDuration: 0.5, animations: {
                self.progressView.alpha = 0
            })
        }
        
    }
    
    
    ///js交互
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        let msg = message.name
        
        
        //微信分享
        if  msg == "shareWeixinInfo" {
            
            //将获取到的数据解析成字典
            let messageDic = message.body as? NSDictionary
            
            if let shareMsg = messageDic {
                //解析取回的字典数据
                titleStr = shareMsg["title"] as! String
                desc = shareMsg["desc"] as! String
                link = shareMsg["link"] as! String
                imgURL = shareMsg["imgUrl"] as! String
                
                shareView = YSJShareView.init(frame: CGRect(x: 0, y: UIScreen.main.bounds.height - 80, width: UIScreen.main.bounds.width, height: 80))
                shareView._delegate = self
                shareView.addItem("QQ", withImage: UIImage(named: "s_QQ")!)
                shareView.addItem("QQ空间", withImage: UIImage(named: "s_QZone")!)
                shareView.addItem("微信朋友圈", withImage: UIImage(named: "wx_Fri")!)
                shareView.addItem("微信好友", withImage: UIImage(named: "wx_Zone")!)
                shareView.layer.cornerRadius = 5
                
                self.view.addSubview(shareView)
                
                shareView.show()
            } else {
                MBManager.showBriefAlert("分享信息错误")
            }
            
            
            
            //微信支付
        } else if msg == "wxpay" {
            
            print("\((#file as NSString).lastPathComponent):(\(#line))\n",message.body)
            
            let wxDic = message.body as? NSDictionary
            
            //XFLog(message: wxDic)
            
            if let wxpayMsg = wxDic {
                
                ///微信支付
                WXTool.shared.sendWXPay(wxDict: wxpayMsg, _com: { (result) in
                    
                    switch result {
                    case "-2":
                        self.hidesBottomBarWhenPushed = true
                        self.navigationController?.pushViewController(PayFailViewController(), animated: true)
                        
                        break
                        
                    case "0":
                        self.hidesBottomBarWhenPushed = true
                        self.navigationController?.pushViewController(PaySuccessVC(), animated: true)
                        
                        break
                        
                    case "-1":
                        self.hidesBottomBarWhenPushed = true
                        self.navigationController?.pushViewController(PayFailViewController(), animated: true)
                        
                        break
                        
                    default:
                        break
                    }
                    
                    //清除URL保存的值
                    mainIndexArray.removeAllObjects()
                    fwqArray.removeAllObjects()
                    commuArray.removeAllObjects()
                    shoppingCarArray.removeAllObjects()
                    jiaoYIArray.removeAllObjects()
                    zhongjiangArray.removeAllObjects()
                    duihuanArray.removeAllObjects()
                    fenxiangArray.removeAllObjects()
                    
                })
                
            } else {
                MBManager.showBriefAlert("微信支付信息不对")
            }
            
            
            ///支付宝
        } else if msg == "alipay" {
            let dic = message.body as? NSDictionary
            
            var signStr = ""
            
            if let alipayMsg = dic {
                if ((alipayMsg["sign"] as? String) != nil) {
                    signStr = alipayMsg["sign"] as! String
                } else {
                    //回调返回值处理
                    return
                }
                
                //接收Web支付回调
                PaymenyModel.shared.alipay(orderString: signStr, comfun: { (result) in
                    
                    
                    switch result {
                    case "用户中途取消":
                        self.hidesBottomBarWhenPushed = true
                        self.navigationController?.pushViewController(PayFailViewController(), animated: true)
                        break
                        
                    case "网页支付成功":
                        self.hidesBottomBarWhenPushed = true
                        self.navigationController?.pushViewController(PaySuccessVC(), animated: true)
                        break
                        
                    case "正在处理中":
                        CustomAlertView.shared.alertWithTitle(strTitle: "正在处理中")
                        break
                        
                    case "网络连接出错":
                        CustomAlertView.shared.alertWithTitle(strTitle: "网络连接出错")
                        //                    self.navigationController?.pushViewController(PaySuccessVC(), animated: true)
                        break
                        
                    case "订单支付失败":
                        self.hidesBottomBarWhenPushed = true
                        self.navigationController?.pushViewController(PayFailViewController(), animated: true)
                        
                        break
                    default:
                        break
                    }
                    
                    
                    //清除URL保存的值
                    mainIndexArray.removeAllObjects()
                    fwqArray.removeAllObjects()
                    commuArray.removeAllObjects()
                    shoppingCarArray.removeAllObjects()
                    jiaoYIArray.removeAllObjects()
                    zhongjiangArray.removeAllObjects()
                    duihuanArray.removeAllObjects()
                    fenxiangArray.removeAllObjects()
                })
                
                ///接收appdelegate代理传回的值
                NotificationCenter.default.addObserver(self, selector: #selector(WKBaseViewController.info(notification:)), name: NSNotification.Name(rawValue: "123"), object: nil)
            } else {
                MBManager.showBriefAlert("支付宝支付信息不对")
            }
            
            
            
        } else if msg == "gotoCart" {
            
            jumpToShop()
        } else if msg == "login" {
            
            self.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(LoginView(), animated: true)
            self.hidesBottomBarWhenPushed = false
            
            shoppingCarArray.add(message.body)
            
        } else if msg == "submit" {
            
            self.wkDelegate?.server()
            
        } else if msg == "detailRocord" {
            
            jumpDetaiRecord()
            
        } else if msg == "backToMain" {
            
            backToMain()
            
            //调到购物车
        } else if msg == "getCartList" {
            
            shopList = message.body as? String
        }
        
    }
    
    
    // MARK:- 交互函数
    /// 返回首页
    func jumpDetaiRecord() -> Void {
        self.navigationController?.pushViewController(JiaoYIVC(), animated: true)
    }
    
    /// 返回首页
    func backToMain() -> Void {
        self.webView = nil
        
        //清除URL保存的值
        mainIndexArray.removeAllObjects()
        fwqArray.removeAllObjects()
        commuArray.removeAllObjects()
        shoppingCarArray.removeAllObjects()
        jiaoYIArray.removeAllObjects()
        zhongjiangArray.removeAllObjects()
        duihuanArray.removeAllObjects()
        fenxiangArray.removeAllObjects()
        
        
        let mainVC = MainViewController()
        mainVC.mvc = LoginView()
        UIApplication.shared.keyWindow?.rootViewController = mainVC
    }
    
    //跳转到购物车页面
    func jumpToShop() -> Void {
        let tabBarController = UIApplication.shared.keyWindow?.rootViewController as! UITabBarController
        tabBarController.selectedIndex = 3
        
    }
    
    
    
    //刷新函数
    func refreshWebView(sender: UIRefreshControl) {
        
        
        StatusBarCheck.shared.networkingStatesFromStatebar { (result) in
            
            if result == "notReachable" {
                
                self.refreshControl.attributedTitle = NSAttributedString(string: "请检查网络设置")
                sender.endRefreshing()
                
            } else {
                
                //判断是否存在网页，若有，则刷新，没有则不刷新
                if self.webView == nil {
                    sender.endRefreshing()
                    
                    let mainVC = MainViewController()
                    UIApplication.shared.keyWindow?.rootViewController = mainVC
                    
                    let tabBarController = UIApplication.shared.keyWindow?.rootViewController as! UITabBarController
                    tabBarController.selectedIndex = 0
                } else if self.situationMark == "true" {
                    
                    //首页断网刷新
                    if NSStringFromClass(self.classForCoder).contains("MainPageView") {
                        if mainIndexArray.lastObject != nil {
                            self.webView.load(URLRequest.init(url: URL.init(string: mainIndexArray.lastObject as! String)!))
                            sender.endRefreshing()
                        }
                        
                    }
                    
                    //服务区断网刷新
                    if NSStringFromClass(self.classForCoder).contains("ServiceView") {
                        if fwqArray.lastObject != nil {
                            self.webView.load(URLRequest.init(url: URL.init(string: fwqArray.lastObject as! String)!))
                            sender.endRefreshing()
                        }
                        
                    }
                    
                    //交流区断网刷新
                    if NSStringFromClass(self.classForCoder).contains("CommuView") {
                        if commuArray.lastObject != nil {
                            self.webView.load(URLRequest.init(url: URL.init(string: commuArray.lastObject as! String)!))
                            sender.endRefreshing()
                        }
                    }
                    
                    //购物断网刷新
                    if NSStringFromClass(self.classForCoder).contains("Shopping") {
                        if shoppingCarArray.lastObject != nil {
                            self.webView.load(URLRequest.init(url: URL.init(string: shoppingCarArray.lastObject as! String)!))
                            sender.endRefreshing()
                        }
                    }
                    
                    //交易区断网刷新
                    if NSStringFromClass(self.classForCoder).contains("JiaoYI") {
                        if jiaoYIArray.lastObject != nil {
                            self.webView.load(URLRequest.init(url: URL.init(string: jiaoYIArray.lastObject as! String)!))
                            sender.endRefreshing()
                        }
                    }
                    
                    //中奖纪录区断网刷新
                    if NSStringFromClass(self.classForCoder).contains("Awa") {
                        if zhongjiangArray.lastObject != nil {
                            self.webView.load(URLRequest.init(url: URL.init(string: zhongjiangArray.lastObject as! String)!))
                            sender.endRefreshing()
                        }
                    }
                    
                    //兑换区断网刷新
                    if NSStringFromClass(self.classForCoder).contains("ChangedRe") {
                        if duihuanArray.lastObject != nil {
                            self.webView.load(URLRequest.init(url: URL.init(string: duihuanArray.lastObject as! String)!))
                            sender.endRefreshing()
                        }
                    } else {
                        self.webView.reload()
                        sender.endRefreshing()
                    }
                    
                } else if self.situationMark != "true" {
                    self.webView.removeFromSuperview()
                    
                    self.webView.reload()
                    
                    self.view.addSubview(self.webView)
                    
                    sender.endRefreshing()
                }
            }
        }
    }
}

// MARK:- 处理收到内存警告---释放webview
extension WKBaseViewController {
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
        self.webView = nil
    }
}

// MARK:- 接收支付宝app接收结果
extension WKBaseViewController {
    func info(notification : NSNotification) -> Void {
        
        let dic = notification.userInfo as? [AnyHashable : NSObject]
        
        if let result = dic?["re"] as? String {
            
            switch result {
            case "用户中途取消":
                self.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(PayFailViewController(), animated: true)
                
                break
                
            case "支付成功":
                
                //清楚购物车信息
                shopList = nil
                self.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(PaySuccessVC(), animated: true)
                
                break
                
            case "正在处理中":
                CustomAlertView.shared.alertWithTitle(strTitle: "正在处理中")
                break
                
            case "网络连接出错":
                CustomAlertView.shared.alertWithTitle(strTitle: "网络连接出错")
                
                break
                
            case "订单支付失败":
                self.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(PayFailViewController(), animated: true)
                
                break
            default:
                break
            }
            
            //清除URL保存的值
            mainIndexArray.removeAllObjects()
            fwqArray.removeAllObjects()
            commuArray.removeAllObjects()
            shoppingCarArray.removeAllObjects()
            jiaoYIArray.removeAllObjects()
            zhongjiangArray.removeAllObjects()
            duihuanArray.removeAllObjects()
            fenxiangArray.removeAllObjects()
            
            
            NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "123"), object: nil)
            
        }
        
    }
    
    
}

// MARK:- 设置webview
extension WKBaseViewController {
    fileprivate func setWebView() -> Void {
        self.webView = WKWebView.init(frame: self.view.bounds)
        view.addSubview(self.webView)
    }
}

extension WKBaseViewController {
    
    /// 设置界面
    func setUI() -> Void {
        ///http://www.jianshu.com/p/879fe48b0eb7
        ///edgesForExtendedLayout------见网页链接
        self.edgesForExtendedLayout = UIRectEdge()
        
        self.setWebView()
        
        //配置webview
        let configuration = WKWebViewConfiguration()
        let userContentController = WKUserContentController()
        
        //添加交互条目
        //分享到微信
        //        userContentController.add(self as WKScriptMessageHandler, name: "shareWeixinInfo")
        userContentController.add(LeakAvoider.init(delegate: self), name: "shareWeixinInfo")
        //微信支付
        //        userContentController.add(self as WKScriptMessageHandler, name: "wxpay")
        userContentController.add(LeakAvoider.init(delegate: self), name: "wxpay")
        
        //支付宝支付
        //        userContentController.add(self as WKScriptMessageHandler, name: "alipay")
        userContentController.add(LeakAvoider.init(delegate: self), name: "alipay")
        
        //登陆
        //        userContentController.add(self as WKScriptMessageHandler, name: "login")
        userContentController.add(LeakAvoider.init(delegate: self), name: "login")
        
        //跳转到购物车
        //        userContentController.add(self as WKScriptMessageHandler, name: "gotoCart")
        userContentController.add(LeakAvoider.init(delegate: self), name: "gotoCart")
        
        //确认提交建议
        //        userContentController.add(self as WKScriptMessageHandler, name: "submit")
        userContentController.add(LeakAvoider.init(delegate: self), name: "submit")
        
        //交易记录
        //        userContentController.add(self as WKScriptMessageHandler, name: "detailRocord")
        userContentController.add(LeakAvoider.init(delegate: self), name: "detailRocord")
        
        //返回首页
        //        userContentController.add(self as WKScriptMessageHandler, name: "backToMain")
        userContentController.add(LeakAvoider.init(delegate: self), name: "backToMain")
        
        //购物车列表
        //        userContentController.add(self as WKScriptMessageHandler, name: "getCartList")
        userContentController.add(LeakAvoider.init(delegate: self), name: "getCartList")
        
        configuration.userContentController = userContentController
        
        // 设置偏好设置
        let preferences = WKPreferences()
        // 在iOS上默认为NO，表示不能自动通过窗口打开
        preferences.javaScriptCanOpenWindowsAutomatically = true
        preferences.minimumFontSize = 10.0
        configuration.preferences = preferences
        configuration.preferences.javaScriptEnabled = true
        configuration.processPool = WKProcessPool()
        
        
        ///由于设置了edgesForExtendedLayout,防止了页面全部控件向上偏移，所以在子页面数大于2的时候，矫正
        if (self.navigationController?.viewControllers.count)! >= 2 {
            let rect = CGRect(x: 0, y: 0, width: SW, height: SH - 64)
            webView = WKWebView.init(frame: rect, configuration: configuration)
        } else {
            let rect = CGRect(x: 0, y: 0, width: SW, height: SH - 112)
            
            webView = WKWebView.init(frame: rect, configuration: configuration)
        }
        
        
        
        ///配置wkwebview代理
        webView.uiDelegate = self
        webView.navigationDelegate = self
        webView.scrollView.bounces = true
        
        webView.scrollView.delegate = self
        
        view.addSubview(webView)
        
        //添加过度效果
        self.webView.alpha = 0
        
        UIView.animate(withDuration: 1.0) {
            self.webView.alpha = 1
        }
        
        //添加进度条
        self.progressView = UIProgressView()
        
        self.progressView.frame = view.bounds
        view.addSubview(self.progressView)
        
        //默认进度条
        self.progressView.progressTintColor = UIColor.orange
        
        
        //添加刷新控件
        self.refreshControl = UIRefreshControl()
        
        //设置刷新控件的位置
        let offset = -0
        self.refreshControl.bounds = CGRect(x: refreshControl.bounds.origin.x, y: CGFloat(offset),
                                            width: refreshControl.bounds.size.width,
                                            height: refreshControl.bounds.size.height)
        self.refreshControl.addTarget(self, action: #selector(refreshWebView(sender:)), for: UIControlEvents.valueChanged)
        self.webView.scrollView.addSubview(refreshControl)
        
        //监听KVO
        webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil) // add observer for key path
        
        
    }
}

// MARK:- 解决蜂窝网受限
extension WKBaseViewController {
    func gotoSet() -> Void {
        self.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(AutoSolVC(), animated: true)
        self.hidesBottomBarWhenPushed = false
        
    }
}

// MARK:- 分享类型
extension WKBaseViewController : YSJShareViewDelegate {
    func shareBtnClick(_ index: Int) {
        switch index {
        case 0:
            
            StatusBarCheck.shared.networkingStatesFromStatebar(_com: { (result) in
                if result == "notReachable" {
                    MBManager.hideAlert()
                    
                    MBManager.showBriefAlert("请检查网络")
                } else {
                    if QQApiInterface.isQQInstalled() == true {
                        MBManager.showBriefAlert("加载分享资源中...")
                        QQTool.shared.qqShare(title: self.titleStr, desc: self.desc, link: self.link, imgUrl: self.imgURL, type: QQApiURLTargetTypeAudio)
                    } else {
                        MBManager.showBriefAlert("未安装QQ或版本不支持")
                    }
                    
                }
            })
            break
        case 1:
            StatusBarCheck.shared.networkingStatesFromStatebar(_com: { (result) in
                if result == "notReachable" {
                    
                    MBManager.hideAlert()
                    MBManager.showBriefAlert("请检查网络")
                    
                    
                } else {
                    if QQApiInterface.isQQInstalled() == true {
                        MBManager.showBriefAlert("加载分享资源中...")
                        QQTool.shared.qqShare(title: self.titleStr, desc: self.desc, link: self.link, imgUrl: self.imgURL, type: QQApiURLTargetTypeAudio)
                    } else {
                        MBManager.showBriefAlert("未安装QQ或版本不支持")
                    }
                }
            })
            
            break
        case 2:
            StatusBarCheck.shared.networkingStatesFromStatebar(_com: { (result) in
                if result == "notReachable" {
                    
                    MBManager.hideAlert()
                    MBManager.showBriefAlert("请检查网络")
                    
                } else {
                    
                    if WXApi.isWXAppInstalled() == true {
                        MBManager.showBriefAlert("加载分享资源中...")
                        
                        WXTool.shared.shareText(title: self.titleStr, desc:self.desc, link: self.link, imgUrl: self.imgURL, shareType: 1)
                    } else {
                        MBManager.showBriefAlert("未安装微信或版本不支持")
                    }
                }
            })
            
            break
        case 3:
            
            StatusBarCheck.shared.networkingStatesFromStatebar(_com: { (result) in
                if result == "notReachable" {
                    MBManager.hideAlert()
                    MBManager.showBriefAlert("请检查网络")
                    
                    
                } else {
                    
                    if WXApi.isWXAppInstalled() == true {
                        MBManager.showBriefAlert("加载分享资源中...")
                        
                        WXTool.shared.shareText(title: self.titleStr, desc:self.desc, link: self.link, imgUrl: self.imgURL, shareType: 0)
                    } else {
                        MBManager.showBriefAlert("未安装微信或版本不支持")
                    }
                }
            })
            
            break
        default:
            break
        }
    }
    
    
}


class LeakAvoider : NSObject, WKScriptMessageHandler {
    weak var delegate : WKScriptMessageHandler?
    init(delegate:WKScriptMessageHandler) {
        self.delegate = delegate
        super.init()
    }
    
    
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        self.delegate?.userContentController(
            userContentController, didReceive: message)
    }
    
}
